package com.yang.core.plugins.auth;

import com.yang.core.api.RestClientBuilder;
import com.yang.core.config.RestClientProperties;
import com.yang.core.extension.ExtensionPoint;
import com.yang.core.extension.RestClientExtension;

/**
 * 认证扩展
 * 开箱即用的认证功能
 */
@ExtensionPoint(
    name = "authentication",
    description = "自动认证扩展，支持多种认证方式",
    category = ExtensionPoint.Category.AUTHENTICATION,
    order = 10
)
public class AuthenticationExtension implements RestClientExtension {

    private final RestClientProperties.Auth authConfig;

    public AuthenticationExtension() {
        this.authConfig = null; // 使用默认配置
    }

    public AuthenticationExtension(RestClientProperties.Auth authConfig) {
        this.authConfig = authConfig;
    }

    @Override
    public void extend(RestClientBuilder builder) {
        RestClientProperties.Auth config = authConfig;

        if (config == null) {
            return;
        }

        switch (config.getType()) {
            case BASIC:
                addBasicAuth(builder, config);
                break;
            case BEARER:
                addBearerAuth(builder, config);
                break;
            case API_KEY:
                addApiKeyAuth(builder, config);
                break;
            case OAUTH2:
                addOAuth2Auth(builder, config);
                break;
            case NONE:
            default:
                // 不添加认证
                break;
        }
    }

    private void addBasicAuth(RestClientBuilder builder, RestClientProperties.Auth config) {
        if (config.getBasicUsername() != null && !config.getBasicUsername().isEmpty()) {
            String credentials = config.getBasicUsername() + ":" + config.getBasicPassword();
            String encodedCredentials = java.util.Base64.getEncoder()
                .encodeToString(credentials.getBytes(java.nio.charset.StandardCharsets.UTF_8));
            builder.defaultHeader("Authorization", "Basic " + encodedCredentials);
        }
    }

    private void addBearerAuth(RestClientBuilder builder, RestClientProperties.Auth config) {
        if (config.getBearerToken() != null && !config.getBearerToken().isEmpty()) {
            builder.defaultHeader("Authorization", "Bearer " + config.getBearerToken());
        }
    }

    private void addApiKeyAuth(RestClientBuilder builder, RestClientProperties.Auth config) {
        if (config.getApiKey() != null && !config.getApiKey().isEmpty()) {
            // 默认在Authorization头中发送API Key
            builder.defaultHeader("Authorization", "ApiKey " + config.getApiKey());
        }
    }

    private void addOAuth2Auth(RestClientBuilder builder, RestClientProperties.Auth config) {
        // 添加OAuth2拦截器
        builder.addInterceptor(new OAuth2Interceptor(config.getOauth2()));
    }
}